Scroll Progress Bar

Nested For Loop

A nested for loop is a loop inside another loop. It allows performing repetitive tasks in a nested or hierarchical manner. The inner loop gets executed completely for each iteration of the outer loop. Nested for loops are useful when dealing with multi-dimensional data structures like matrices or when need to perform tasks that have multiple levels of repetition.

Example of nested for loops to print a pattern of stars in the shape of a triangle.


#include <stdio.h>

int main() {
    int rows;

    printf("Enter the number of rows for the triangle: ");
    scanf("%d", &rows);

    for (int i = 1; i <= rows; i++) {          // Outer loop to control the rows
        for (int j = 1; j <= i; j++) {         // Inner loop to control the number of stars in each row
            printf("* ");
        }
        printf("\n");                          // Move to the next line after each row is printed
    }

    return 0;
}
Explanation of the Program:
  • The program takes input from the user to determine the number of rows (rows) for the triangle pattern.
  • The outer for loop is used to control the number of rows in the triangle. It starts from i = 1 and continues as long as i is less than or equal to the rows. After each iteration, i is incremented by 1.
  • The inner for loop is used to print the stars in each row. It starts from j = 1 and continues as long as j is less than or equal to i (the current row number in the outer loop). After each iteration, j is incremented by 1.
  • Inside the inner loop, printf("* ") prints a single star followedby a space.
  • After printing all the stars in a row (inner loop completes), printf("\n") is used to move to the next line and start the next row.
Sample Output (for rows = 5):

* 
* * 
* * * 
* * * * 
* * * * *

The nested for loop efficiently prints the pattern of stars in the shape of a triangle with the specified number of rows. The inner loop prints the stars, and the outer loop controls the number of rows to create the desired pattern.


What is a nested for loop in C used for?


Iteration

What does the inner loop do in a nested for loop?


Iterate

What is the primary purpose of using nested for loops in C?


Nestedness